package alpha.com.google.code.mechanic.janitor.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;

/**
 * The class is to decompress a zip file to a specified directory.
 * 
 * @Last_edited: Nov 1, 2014
 * 
 * @author jingjiejiang
 * @since Oct 31, 2014
 */
public class UnZipFiles {
  
  private String srcZipFile;
  private String dstnFile;
  
  public UnZipFiles(String srcFile, String dstnFile) {
    
    srcZipFile = srcFile;
    this.dstnFile = dstnFile;
  }
  
  public boolean decompressZipFile() {
    
    byte[] buffer = new byte[1024];
    
    try {
      
      File path = new File(dstnFile);
      if (false == path.exists()) {
        path.mkdir();
      }
      ZipInputStream input = new ZipInputStream(new FileInputStream(srcZipFile));
      // Get the file list entry of the source zip file.
      ZipEntry entry = input.getNextEntry();
      while (entry != null) {
        
        String filename = entry.getName();
        File newfile = new File(dstnFile + File.separator + filename);
        
        if (entry.isDirectory()) {
          new File(newfile.getParent()).mkdirs();
        }
        else {
          // Create all non exists folders
          new File(newfile.getParent()).mkdirs();
          FileOutputStream output = new FileOutputStream(newfile);
          int len;
          while ((len = input.read(buffer)) > 0) {
            output.write(buffer, 0, len);
          }
          
          output.close();
        }

        entry = input.getNextEntry();
      }
      
      input.closeEntry();
      input.close();
      
      return true;
      
    } catch (IOException e) {
      Shell pshell = Display.getCurrent().getActiveShell();
      MessageDialog.openError(pshell, "Couldn't decompress the Zip file: "
        + srcZipFile, e.getMessage());
      return false;
    }
  }

}
